﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace SO_DataFetcher.PubFunctions.DataBaseHelp
{
    public class SqlServerHelp:DataBaseHelper
    { 
        private static SqlServerHelp _instance;

        public override void Instance()
        {
            _instance = new SqlServerHelp();
        }

        private SqlConnection _sqlConnection;
        private SqlConnection SqlConnection
        {
            get { return _sqlConnection ?? (_sqlConnection = new SqlConnection(_instance.Connecting)); }
        }

        /// <summary>
        /// 创建连接字符串
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="name"></param>
        /// <param name="psw"></param>
        /// <param name="dataTable"></param>
        public override void GetConnectString(string ip, string port, string name, string psw, string dataTable)
        {

            if (!string.IsNullOrEmpty(port))
            {
                _instance.Connecting = string.Format("Server={0},{1};Database={2};User ID={3};Password={4};Trusted_Connection=False", ip, port, dataTable, name, psw);
            }
            else
            {
                _instance.Connecting = string.Format("Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False", ip, port, name, psw);
            }
        }

        public override void ExecuteSql(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, _instance.SqlConnection);
            try
            {
                OpenConnection();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                CloseConnection();
            }
        }

        public override DataSet GetDataSet(string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                OpenConnection();
                SqlDataAdapter adapter = new SqlDataAdapter(sql, _instance.SqlConnection);
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                CloseConnection();
            }

            return ds;
        }

        public override void OpenConnection()
        {
            if (_instance.SqlConnection.State == ConnectionState.Closed)
                _instance.SqlConnection.Open();
        }

        public override void CloseConnection()
        {
            if (_instance.SqlConnection.State == ConnectionState.Open)
                _instance.SqlConnection.Close();
        }

    }
}
